package de.tuhrig.sportlog.servlets;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import de.tuhrig.sportlog.pmf.PMF;
import de.tuhrig.sportlog.user.log.Log;

public class PostNewLogServlet extends HttpServlet {
	
	private static final Logger logger = Logger.getLogger(PostNewLogServlet.class.getName());
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private final DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
	
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
	
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();

		if (user != null) {

			Log log = new Log();

			log.setUserId(user.getUserId());
			log.setComment(req.getParameter("comment"));
			log.setLocation(req.getParameter("location"));
			
			DateFormat sdf = new SimpleDateFormat("hh:mm a");
			
			try {
				
				log.setDate(df.parse(req.getParameter("date")));
				log.setStart(sdf.parse(req.getParameter("start")));
				log.setEnd(sdf.parse(req.getParameter("end")));
			}
			catch (ParseException e) {
				
				logger.log(Level.WARNING, "", e);
			}
			
			try {
				
				log.createWeather();
			} 
			catch (SAXException e) {
				
				logger.log(Level.WARNING, "", e);
			} 
			catch (ParserConfigurationException e) {

				logger.log(Level.WARNING, "", e);
			}
			
			log.setSport(Log.parseSport(req.getParameter("sport")));
			
			logger.log(Level.INFO, log.toString());
			
			PersistenceManager pm = PMF.get().getPersistenceManager();

			try {

				pm.makePersistent(log);
			} 
			finally {

				pm.close();
			}
		}
		
		resp.sendRedirect("/jsp/Logs.jsp");
	}
}